package com.epfresh.supplier.view;

import android.app.Dialog;
import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;

import com.aigestudio.wheelpicker.core.AbstractWheelPicker;
import com.aigestudio.wheelpicker.core.IWheelPicker;
import com.aigestudio.wheelpicker.view.WheelStraightPicker;
import com.epfresh.api.utils.L;
import com.epfresh.api.utils.LocalDisplay;
import com.epfresh.supplier.R;
import com.epfresh.supplier.entity.CityAddressList;
import com.epfresh.supplier.entity.CityMap;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class AreaDialog extends Dialog implements View.OnClickListener {
    private View root;
    private ViewGroup container;
    private IWheelPicker picker;

    private int index1;
    private int index2;
    private int index3;
    private String data1;
    private String data2;
    private String data3;

    private WheelStraightPicker wheelUnit1;
    private WheelStraightPicker wheelUnit2;
    private WheelStraightPicker wheelUnit3;

    private OnPositiveClickListener onPositiveClickListener;
    private boolean isFirst;

    public AreaDialog(Context context) {
        super(context);
        Context mContext = context;
        int padding = LocalDisplay.dp2px(18);
        int textSize = LocalDisplay.dp2px(20);
        int itemSpace = LocalDisplay.dp2px(20);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        setCanceledOnTouchOutside(true);


        root = getLayoutInflater().inflate(R.layout.dialog_new_layout, null);
        container = (ViewGroup) root.findViewById(R.id.content);
        container.removeAllViews();
        Button rButton = (Button) root.findViewById(R.id.positiveButton);
        rButton.setOnClickListener(this);
        Button lButton = (Button) root.findViewById(R.id.negativeButton);
        lButton.setOnClickListener(this);


        setTitle("省市区选择");
        View v = LayoutInflater.from(getContext()).inflate(R.layout.dialog_area, null);
        setContentView(v);

        wheelUnit1 = (WheelStraightPicker) findViewById(R.id.wheel_unit_1);
        wheelUnit2 = (WheelStraightPicker) findViewById(R.id.wheel_unit_2);
        wheelUnit3 = (WheelStraightPicker) findViewById(R.id.wheel_unit_3);

    }

    public void setData(CityMap city, int index1, int index2, int index3) {
        if (city == null){
            return;
        }
//        this.city = city;
        isFirst = true;
        updateCityStatus(0, city, index1, index2, index3);
        wheelUnit1.setOnWheelChangeListener(new AbstractWheelPicker.OnWheelChangeListener() {
            @Override
            public void onWheelScrolling(float deltaX, float deltaY) {

            }

            @Override
            public void onWheelSelected(int index, String data) {
                data1 = data;

                if (!isFirst) {
                    AreaDialog.this.index1 = index;
                    AreaDialog.this.index2 = 0;
                    AreaDialog.this.index3 = 0;
                    L.e("index", "---------------------");
                    L.e("index", "p:" + AreaDialog.this.index1);
                    L.e("index", "c:" + AreaDialog.this.index2);
                    L.e("index", "s:" + AreaDialog.this.index3);
                    L.e("index", "---------------------");
                    //选择省，要联动市、县
                    updateCityStatus(1, AreaDialog.this.city, index, AreaDialog.this.index2, AreaDialog.this.index3);
                }

            }

            @Override
            public void onWheelScrollStateChanged(int state) {

            }
        });
        wheelUnit2.setOnWheelChangeListener(new AbstractWheelPicker.OnWheelChangeListener() {
            @Override
            public void onWheelScrolling(float deltaX, float deltaY) {

            }

            @Override
            public void onWheelSelected(int index, String data) {
                data2 = data;
                if (!isFirst) {
                    AreaDialog.this.index2 = index;
                    AreaDialog.this.index3 = 0;
                    L.e("index", "index:" + index);
                    L.e("index", "p:" + AreaDialog.this.index1);
                    L.e("index", "c:" + AreaDialog.this.index2);
                    L.e("index", "s:" + AreaDialog.this.index3);
                    //选择市，要联动市、县
                    updateCityStatus(2, AreaDialog.this.city, AreaDialog.this.index1, index, AreaDialog.this.index3);
                }
                isFirst = false;
            }

            @Override
            public void onWheelScrollStateChanged(int state) {

                isFirst = false;
            }
        });
        wheelUnit3.setOnWheelChangeListener(new AbstractWheelPicker.OnWheelChangeListener() {
            @Override
            public void onWheelScrolling(float deltaX, float deltaY) {

            }

            @Override
            public void onWheelSelected(int index, String data) {
                data3 = data;
                AreaDialog.this.index3 = index;
            }

            @Override
            public void onWheelScrollStateChanged(int state) {

            }
        });

    }

    public void updateCityStatus(int type, CityMap city, int index1, int index2, int index3) {
        this.city = city;
        if (city == null) {
            return;
        }
        if (index1 < 0) {
            index1 = 0;
        }
        if (index2 < 0) {
            index2 = 0;
        }
        if (index3 < 0) {
            index3 = 0;
        }

        ArrayList<CityAddressList> addressList = city.getAddressList();
        //获取省级
        List<String> list1 = getCityList(addressList);
        if (list1.size() < index1) {
            index1 = 0;
        }

        CityAddressList cityAddressList = addressList.get(index1);

        ArrayList<CityAddressList> children = cityAddressList.getChildren();
        //获取省对应的市级
        List<String> list2 = getCityList(children);

        if (list2.size() < index2) {
            index2 = 0;
        }

        CityAddressList cityAddressList1 = children.get(index2);

        ArrayList<CityAddressList> children1 = cityAddressList1.getChildren();

        //获取市级对应的县
        List<String> list3 = getCityList(children1);

        if (list3.size() < index3) {
            index3 = 0;
        }

        L.e("index", "index:" + index1);
        L.e("index", "index:" + index2);
        L.e("index", "index:" + index3);

        if (type == 0) {
            wheelUnit1.setData(list1,index1);
            wheelUnit2.setData(list2,index2);
            wheelUnit3.setData(list3,index3);
            this.index1 = index1;
            this.index2 = index2;
            this.index3 = index3;
        } else if (type == 1) {
            wheelUnit2.setData(list2,index2);
            wheelUnit3.setData(list3,index3);
            this.index2 = index2;
            this.index3 = index3;
        } else {
            wheelUnit3.setData(list3,index3);
            this.index3 = index3;
        }




    }


    public List<String> getCityList(ArrayList<CityAddressList> citys) {

        List<String> list1 = new ArrayList<>();
        if(citys==null)
            return list1;
        for (int i = 0; i < citys.size(); i++) {
            if(citys.get(i)==null)
                continue;
            list1.add(citys.get(i).getName());
        }

        return list1;
    }

    @Override
    public void setContentView(View view) {
        container.addView(view);
        super.setContentView(root);
        Window dialogWindow = getWindow();
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = LocalDisplay.SCREEN_WIDTH_PIXELS;
        dialogWindow.setAttributes(lp);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.positiveButton:

                if (isPositiveDismiss)
                    dismiss();
                if (onPositiveClickListener != null) {
                    CityAddressList city1 ;
                    CityAddressList city2 ;
                    CityAddressList city3 ;
                    if (city != null&&city.getAddressList() != null&&city.getAddressList().size()>index1){
                        city1 = city.getAddressList().get(index1);

                        city2 = city.getAddressList().get(index1).getChildren().get(index2);
                        city3= city.getAddressList().get(index1).getChildren().get(index2).getChildren().get(index3);

                        onPositiveClickListener.onPositiveClickListener(index1, city1, index2, city2,index3,city3);
                    }
                }
                break;
            case R.id.negativeButton:
                dismiss();
                break;
        }
    }


    public OnPositiveClickListener getOnPositiveClickListener() {
        return onPositiveClickListener;
    }

    public void setOnPositiveClickListener(OnPositiveClickListener onPositiveClickListener) {
        this.onPositiveClickListener = onPositiveClickListener;
    }

    public void setTitle(String title) {
        ((TextView) root.findViewById(R.id.title)).setText(title);
    }

    public void setLeftText(String text) {
        ((TextView) root.findViewById(R.id.negativeButton)).setText(text);
    }

    public void setRightText(String text) {
        ((TextView) root.findViewById(R.id.positiveButton)).setText(text);
    }

    public boolean isPositiveDismiss() {
        return isPositiveDismiss;
    }

    public void setPositiveDismiss(boolean positiveDismiss) {
        isPositiveDismiss = positiveDismiss;
    }

    public void setCurrentItem(int index1, int index2) {
        wheelUnit1.setItemIndex(index1);
        wheelUnit2.setItemIndex(index2);
    }

    private boolean isPositiveDismiss;


    public interface OnPositiveClickListener {
        public void onPositiveClickListener(int index1, CityAddressList city1, int index2, CityAddressList city2, int index3, CityAddressList city3);

    }


    private CityMap city;

    public void setCurrentIndex(CityMap city, String provinceId, String cityId, String districtId) {
        if (provinceId != null && cityId != null && districtId != null
                && !"".equals(provinceId)
                && !"".equals(cityId)
                && !"".equals(districtId)) {
            int i1 = 0;
            int i2 = 0;
            int i3 = 0;

            ArrayList<CityAddressList> addressList = city.getAddressList();

            for (int i = 0; i < addressList.size(); i++) {
                CityAddressList cityAddressList = addressList.get(i);
                String code = cityAddressList.getCode();
                if (provinceId.equals(code)) {
                    i1 = i;
                    ArrayList<CityAddressList> children = cityAddressList.getChildren();

                    for (int j = 0; j < children.size(); j++) {
                        CityAddressList cityAddressList1 = children.get(j);
                        if (cityId.equals(cityAddressList1.getCode())) {
                            i2 = j;

                            ArrayList<CityAddressList> children1 = cityAddressList1.getChildren();

                            for (int k = 0; k < children1.size(); k++) {
                                CityAddressList cityAddressList2 = children1.get(k);
                                if (districtId.equals(cityAddressList2.getCode())) {
                                    i3 = k;
                                }
                            }
                        }
                    }

                }
            }
            setData(city, i1, i2, i3);
        }else {
            setData(city, 0, 0, 0);
        }
    }

    public int getItem1(CityMap city, int index) {
        int cityIndex = 0;
        ArrayList<CityAddressList> addressList = city.getAddressList();
        for (int i = 0; i < addressList.size(); i++) {
            CityAddressList cityAddressList = addressList.get(i);
            String name = cityAddressList.getName();

        }
        return cityIndex;
    }

    public CityMap getCityData() {
        String cityDataStr = "";
        CityMap city = null;
        AssetManager asset = getContext().getAssets();
        InputStream input = null;
        try {
            input = asset.open("epfresh_area_data");
            BufferedReader bufferedReader = new BufferedReader(
                    new InputStreamReader(input));
            StringBuilder stringBuilder = new StringBuilder();
            while ((cityDataStr = bufferedReader.readLine()) != null) {
                stringBuilder.append(cityDataStr);
            }
            bufferedReader.close();
            input.close();
            cityDataStr = stringBuilder.toString();//创建超长string
            if (cityDataStr != null && !"".equals(cityDataStr)) {

                JSONObject jsonObject = new JSONObject(cityDataStr);

                String response = jsonObject.getString("response");

                city = new Gson().fromJson(response.trim(), CityMap.class);

            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return city;
    }
}